import { updateQueue } from "./reactComponent";
//合成事件

/**
 * 给DOM添加合成事件
 * 1. 面向aop，给handler前后增加一些操作
 * 2. 处理浏览器兼容性，提供兼容所有浏览器的统一api，屏蔽浏览器差异
 * 3. 模拟事件冒泡 和阻止冒泡
 * @param {*} dom
 * @param {*} eventType
 * @param {*} handler
 */
export function addEvent(dom, eventType, handler) {
  let store = dom.store || (dom.store = {});
  store[eventType] = handler;
  document[eventType] = dispatchEvent;
}

function dispatchEvent(nativeEvent) {
  updateQueue.isBatchingUpdate = true;
  //type: click; target 事件源DOM。点击的是button的话就是button
  let { type, target } = nativeEvent;
  let eventType = `on${type}`;
  //创建合成事件
  let syntheticEvent = createSyntheticEvent(nativeEvent);
  while (target) {
    let { store } = target;
    let handler = store && store[eventType];
    if (handler) handler(syntheticEvent);
    //阻止冒泡 跳出循环
    if (syntheticEvent.isPropagationStopped) {
      break;
    }
    target = target.parentNode;
  }
  updateQueue.isBatchingUpdate = false;
  updateQueue.batchUpdate();
}

function createSyntheticEvent(nativeEvent) {
  let syncthetic = {};

  for (let key in nativeEvent) {
    let value = nativeEvent[key];
    if (typeof value === "function") {
      value = value.bind(nativeEvent);
    }
    syncthetic[key] = value;
  }
  syncthetic.nativeEvent = nativeEvent;
  syncthetic.stopPrapagation = stopPropagation; //阻止冒泡
  syncthetic.isPropagationStopped = false; //是否已经阻止冒泡
  syncthetic.preventDefault = preventDefault; //阻止默认事件
  syncthetic.defaultPrevented = false;
  return syncthetic;
}

function stopPropagation() {
  const event = this.nativeEvent;
  if (event.stopPropagation) {
    event.stopPropagation();
  } else {
    event.cancelBubble = true;
  }
  this.isPropagationStopped = true;
}

function preventDefault() {
  const event = this.nativeEvent;
  if (event.preventDefault) {
    event.preventDefault();
  } else {
    event.returnValue = false;
  }
  this.defaultPrevented = true;
}
